package com.bsoft.gol.editor.fileUpload;



import com.bsoft.gol.editor.dao.EditorOrganizationDAO;
import com.bsoft.gol.editor.dao.EditorUserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CountDownLatch;


@Service("userDataUpdater")
public class UserDataUpdater implements DataUpdateHandler<UserHolder>{

	@Autowired
	private EditorUserDAO editorUserDAO;
	@Autowired
	private EditorOrganizationDAO editorOrganizationDAO;

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor4BaseDataImport;
	
	private int countPerTask = CommConst.DEFAULT_TASK_PER_USER_NUM;//任务单个处理个数，科室存在上下级，所以这个数就是个概数。且可以通过xml注入
	
	@Override
	public void saveData(TableData<UserHolder> tableData) throws Exception{
		int total = tableData.getCount().get();//总数
		countPerTask = countPerTask > 0 ? countPerTask : CommConst.DEFAULT_TASK_PER_USER_NUM;
		int taskCount = total == countPerTask ? 1 : total/countPerTask + 1;
		if(taskCount > CommConst.TASK_LIMIT_USER){//超过限制后，重新根据任务数上限计算每个任务处理的记录数[有效记录，通过校验的]
			taskCount = CommConst.TASK_LIMIT_USER;
			countPerTask = total / taskCount + 1;
		}
		if(taskCount == 1){
			new UserDataImportTask(null,editorUserDAO,editorOrganizationDAO,tableData).run();
		}else if(taskCount > 0){
			CountDownLatch countDownLatch = new CountDownLatch(taskCount);
			int start = 0;
			int end = 0;
			int limit = total - 1;//界限
			List<UserHolder> rows = tableData.getRowData();
			for(int j = 0 ; j < taskCount; j ++ ){
				int count4Task = 0;//当前任务处理的记录数累计值
				for(int k = start; k < total; k ++ ){
					UserHolder holder = rows.get(k);
					if(!holder.isValid()){
						continue;
					}
					count4Task ++;
					if(count4Task == countPerTask || k == limit){
						end = k;
						break;
					}
				}
				end = end + 1;//与taskCount == 1分支执行时候保持一致，任务表里的时候从start开始，结束于end(<end)
				Runnable task = new UserDataImportTask(countDownLatch,editorUserDAO,editorOrganizationDAO,tableData,start,end);
				start = end;
				taskExecutor4BaseDataImport.execute(task);
			}
			try {
				countDownLatch.await();//等待所有任务处理完
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	
	}

}
